package de.jamm.aws;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import de.hshannover.inform.muehle.strategy.Strategy;
//test
public class ClassLoaderKI {
	private static Strategy[] allStrategys;
	public static void loadKIClasses(){
		//BLOCK: KI Ordner einlesen
		File a = new File("strategies");
		//--------------------------------------------------------
		
		//BLOCK: potentielle KIs finden
		File[] allJars = getJarsFromFolder(a);
		//--------------------------------------------------------
		
		HashSet<Strategy> rtn = new HashSet<Strategy>();
		
		for(File curr:allJars){
			try {
				URLClassLoader clazzLoader = URLClassLoader.newInstance(new URL[]{curr.toURI().toURL()});
				
				JarFile jarFile = new JarFile(curr);
		        Enumeration<JarEntry> entries = jarFile.entries();
		        
		        while (entries.hasMoreElements()) {
		            JarEntry element = entries.nextElement();
		            if (element.getName().endsWith(".class")) {
		                try {
		                    Class<?> c = clazzLoader.loadClass(element.getName().replaceAll(".class", "").replaceAll("/", "."));
		                    for(Class<?> test:c.getInterfaces()){
		                    	if(test.getName().equals("de.hshannover.inform.muehle.strategy.Strategy")){
		                    		Strategy rtnStrategy = (Strategy) c.newInstance();
		                    		rtn.add(rtnStrategy);
		                    	}
		                    }
		                } catch (Exception e) {
		                    e.printStackTrace();
		                }
		            }
		        }
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		allStrategys = rtn.toArray(new Strategy[]{});
	}
	private static File[] getJarsFromFolder(File a) {
		// TODO Auto-generated method stub
		HashSet<File> rtn = new HashSet<File>();
		for(File temp:a.listFiles()){
			if(temp.isFile() && temp.getName().endsWith(".jar")){
					rtn.add(temp);
			}
		}
		return rtn.toArray(new File[]{});
	}
	public static Strategy[] getAllStrategys() {
		if(allStrategys == null){
			loadKIClasses();
		}
		return allStrategys;
	}
	public static void refreshKIList(){
		loadKIClasses();
	}
	public static void setAllStrategys(Strategy[] allStrategys) {
		ClassLoaderKI.allStrategys = allStrategys;
	}
}
